import Arrow from "@assets/arrow.png";
import BackgroundImg from "@assets/bg02.jpg";
import CreateButton from "@assets/create_button.png";
import Label1 from "@assets/label1.png";
import Label2 from "@assets/label2.png";
import SmallDragon from "@assets/small_dragon.png";

import BaseBackground from "@plugin/BaseBackground";
import EnhanceUseNavigate from "@plugin/EnhanceUseNavigate";
import React, { Component } from "react";
import styles from "./index.module.scss";

import { complexVideo } from "@api";
import { ActionSheet, Dialog, Toast } from "react-vant";
import PersonalInformation from "../../../plugin/PersonalInformation";
import { getChannel } from "../../../utils";
import { CampaignIds } from "../../../utils/ha.common";

const options = [
  {
    name: "财神爷爷笑哈哈，红包满满乐开花",
  },
  {
    name: "日日夜夜多喜乐，岁岁年年长安康",
  },
  {
    name: "龙年学业步步升，一飞冲天跃龙门",
  },
  {
    name: "龙年顺心又顺意，日子甜甜又蜜蜜",
  },
  {
    name: "升职加薪步步高，钱多事少心情好",
  },
];

class Index extends Component {
  constructor(props) {
    super(props);

    this.state = {
      role: "",
      divWish: "",
      optionValue: options[0].name,
      placeholderEnd: 21,
      actionSheetVisible: false,
    };

    this.PRef = React.createRef();
  }

  componentDidMount() {
    window._ha("send", "action", "cny_activity1_blessingtypepage_view", {
      campaign_id: CampaignIds.activity1,
      channel: getChannel(),
    });
  }

  handlerChangeRoles = (e) => {
    this.setState({
      role: e.target.value,
    });
  };

  handlerChangeOptions = (e) => {
    this.setState({
      optionValue: e.target.value,
    });
  };

  handlerChangeDivWish = (e) => {
    const value = e.target.value;
    this.setState({
      divWish: value,
    });
    const canNotSubmitPrefix =
      "祝、祝您、祝福您、祝你、祝福你、祝愿你、祝愿您".split("、");
    if (
      canNotSubmitPrefix.find((i) => value.includes(i) && !value.startsWith(i))
    ) {
      Toast("祝福语已包括“祝你”啦，请确认祝福内容是否需要调整。");
    }
  };

  handlerClick = async () => {
    const { role, divWish, optionValue } = this.state;

    if (
      divWish &&
      !/^[\u4e00-\u9fa5a-zA-Z0-9,.?!;:()（）。，？！；：]+$/.test(divWish)
    )
      return Toast("不能输入特殊字符哦~");

    const t1 = Toast.loading({
      message: "请稍等",
      forbidClick: false,
    });

    complexVideo({
      text: `亲爱的${role || "朋友"},祝您${divWish || optionValue}`,
      nick: role || "朋友",
      greeting: divWish || optionValue,
    })
      .then((res) => {
        if (res["state"] === "ok") {
          sessionStorage.setItem("TASK_ID", res["data"]["id"]);
          this.props.navigate("/activity_loading_1");
        }
      })
      .catch((err) => {
        Dialog.alert({
          title: "服务异常",
          message: JSON.stringify(err),
        });
      })
      .finally(() => {
        t1.clear();
      });

    window._ha(
      "send",
      "action",
      "cny_activity1_blessingtypepage_makevideo_click",
      {
        campaign_id: CampaignIds.activity1,
        channel: getChannel(),
        text: `亲爱的${role},祝您${divWish || optionValue}`,
      }
    );
  };

  render() {
    const { role, divWish, optionValue } = this.state;
    return (
      <>
        <BaseBackground backgroundImage={BackgroundImg} showFlag={true}>
          <div className={styles.form_box}>
            <div className={styles.form_box}>
              <div className={styles.form_item}>
                <img src={Label1} className={styles.label1} alt="" />
                <input
                  type="text"
                  onChange={this.handlerChangeRoles}
                  value={role}
                  className={styles.input}
                  maxLength={10}
                  placeholder="TA的名字(2-5中文 或 4-10英文字母）"
                />
              </div>
              <div className={styles.form_item}>
                <img src={Label2} className={styles.label2} alt="" />
                <div
                  className={styles.select_item}
                  onClick={() => {
                    this.setState({
                      actionSheetVisible: true,
                    });
                  }}
                >
                  <div className={styles.select_content}>{optionValue}</div>
                  <img src={Arrow} className={styles.arrow} alt="" />
                </div>
                <div
                  style={{
                    position: "relative",
                  }}
                >
                  <input
                    type="text"
                    onChange={this.handlerChangeDivWish}
                    value={divWish}
                    className={styles.input}
                    placeholder={`我想自己写(8-14字,仅限中文)`}
                    maxLength={14}
                  />
                </div>
              </div>

              <div className={styles.rmk}>
                请确保您提交的内容中没有不符合活动规则中“提交作品须知”的内容。
                若您提交的内容中涉及个人信息，我们将按照{" "}
                <span
                  onClick={() => this.PRef.open()}
                  style={{
                    textDecoration: "underline",
                  }}
                >
                  《个人信息处理规则》
                </span>
                处理， 点击下方“生成视频”按钮，即视为您已阅读并同意该规则。
              </div>

              <div>
                <img src={SmallDragon} className={styles.small_dragon} alt="" />
              </div>
              <div>
                <div className={styles.create_rmk}>
                  视频语音采用阿里云语音合成技术生成
                </div>
                <img
                  onClick={this.handlerClick}
                  src={CreateButton}
                  className={styles.create_button}
                  alt=""
                />
              </div>
            </div>
          </div>
        </BaseBackground>

        <ActionSheet
          description="任选一句为TA送上祝福吧"
          onCancel={() => {
            this.setState({
              actionSheetVisible: false,
            });
          }}
          cancelText="关闭"
          visible={this.state.actionSheetVisible}
          actions={options}
          onSelect={(aciton) => {
            this.setState({
              optionValue: aciton.name,
              actionSheetVisible: false,
            });
          }}
        />

        <PersonalInformation ref={(ref) => (this.PRef = ref)} />
      </>
    );
  }
}

export default EnhanceUseNavigate(Index);
